<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
function distributor_assign_salesman_page()
{
    @$output = drupal_render(drupal_get_form('distributor_assign_salesman_form'));
    return $output;
}

function distributor_assign_salesman_form($form, &$form_state)
{
    $form['fist']['#markup']='<label>第一步 选择经销商</label>';
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state);
    $form['address'] = _insert_address_selection_form($form, $form_state,'address', 3, FALSE, '','','',TRUE);
    $form['distributor_fuzzy_search']['#markup'] = '<div class="distributor-fuzzy-search">';

    $form['distributor'] = array(
        '#attributes' => array('placeholder' => '经销商名称','id'=>'distributor_option'),
        '#type' => 'textfield',
        '#default_value' => !empty($form_state['values']['plant']) ? $form_state['values']['plant'] : '',

    );
    $form['cell'] = array(

        '#type' => 'textfield',
        '#default_value' => !empty($form_state['values']['cell']) ? $form_state['values']['cell'] : '',
        '#attributes' => array('placeholder' => '手机'),
        '#validated' => TRUE,
    );
    $form['distributor_fuzzy_search_close']['#markup'] = '</div>';
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    $form['next']['#markup']='<label>第二步 选择销售员</label>';
    $form['salesman'] = _insert_salesman_distributor_selection_form($form, $form_state, 'salesman','', $level = 2);
    $form['assign']['#markup'] = '<a href="javascript:void(0)" id="distributor_assign_salesman" data-toggle="modal" class="btn btn-mini btn-primary">分配</a>';

    return $form;
}

function distributor_assign_salesman_form_validate($form, &$form_state)
{
}

function data_list_view_page($form = '', &$form_state = '')
{
        $output = '';
        //表头
        $header = array(
            array('data' => '<label href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="">全选</label>', 'class' => ['essential no']),
            array('data' => '经销商名称', 'class' => ['essential distributor']),
            array('data' => '省 市 县', 'class' => ['essential province city county ']),
            array('data' => '手机号码', 'class' => ['essential cell']),
            array('data' => '销售员', 'class' => ['essential salesman'],'field' => 'employee_name'),
        );
        $query = db_select('addr', 'A')->extend('PagerDefault')->extend('TableSort');//地址表
        $query->join('distributor', 'D', 'A.addr_id=D.addr_id');//内连接 成一个表
        $query->fields('D');
        $query->leftjoin('salesman_distributor_map','m','m.distributor_id = D.distributor_id');
        $query->leftjoin('employee','e','e.employee_id = m.salesman_id');
        $query->addField('e','employee_name','salesman_name');
        $query->condition('D.status', "经销商", '=');

        //地址级别查询
        _address_search_conditon($query,$form_state);

        //模糊条件筛选
        if (!empty($form_state['values']['cell'])) {//模糊手机查询条件
            $query->condition('D.cell', '%' . db_like($form_state['values']['cell']) . '%', 'LIKE');
        }

        if (!empty($form_state['values']['distributor'])) {//模糊名字查询条件
            $distributor_id = get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor'],false);
            $query->condition('D.distributor_id',!empty($distributor_id)?$distributor_id:0, '=');
        }

        $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
        $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
        $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
        $query->addField('A1', 'name', 'province');
        $query->addField('A2', 'name', 'city');
        $query->addField('A3', 'name', 'county');
        $query->limit(variable_get("list_page_item_number", 10));
        $distributorInfo = $query->orderByHeader($header)->execute();

        $rows = array();
        //表内容
        $n = 1;
        foreach ($distributorInfo as $row) {
            $city = $row->city ? ' '.$row->city :'';
            $county = $row->county ? ' '.$row->county :'';
            $rows[] = array(
                array('data' => '<input type="checkbox" class="listViewTableCheck" value ="' . $row->distributor_id . '"/>' . $n++, 'class' => ['integrant essential no']),
                array('data' =>'<a href="'.base_path().'distributor/edit/' . $row->distributor_id . '" data-toggle="modal" target = "_blank">'. $row->distributor_name.'</a>', 'class' => ['integrant essential distributor']),
                array('data' => $row->province.$city.$county, 'class' => ['essential province']),
                array('data' => $row->cell, 'class' => ['integrant haveTobr goRight essential cell']),
                array('data' => $row->salesman_name, 'class' => ['integrant essential salesman']),
            );
        }

        $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
        /*	 * *按钮** */
        $output .= theme('pager');
        return $output;
//    }
}

function distributor_assign_salesman_delete()
{
    ajax_table_delete('salesman_distributor_map', 'map_id');
}
function distributor_assign_salesman_assign(){
    if(isset($_POST['ids'])){
        $ids = $_POST['ids'];
        unset($_POST['ids']);
    }
    if(isset($_POST['salesman_id'])){
        $salesman_id = $_POST['salesman_id'];
        unset($_POST['salesman_id']);
    }
    $transaction = db_transaction();//数据库事务

    global $user;
    try{
        if (!empty($ids)) { //add new salesman_distributor_map
            foreach ($ids  as  $distributor_id) {
                $nid = db_insert('salesman_distributor_map')// Table name no longer needs {}
                ->fields(array(
                    'salesman_id' => $salesman_id,
                    'distributor_id' => $distributor_id,
                    'author_uid' => $user->uid,
                    'timestamp' => time(),))
                    ->execute();
            }
        }
        $result = array ('success'=>0,'errorNum'=>0);
        echo json_encode($result);

    }catch (Exception $e) {
        $transaction->rollback();
        $result = array ('success'=>1,'errorNum'=>0);
        echo json_encode($result);
    }

}
